import {Result} from "../util/type";
import router from "../router";
import say from "../util/say";

export class ResponseHandleTemplate<T> {
    public constructor(success: (json: Result<T>) => void) {
        this.success = success;
    }

    private success: (json: Result<T>) => void;

    private fail() {
        say.sayError('请先登录')
        router.push('/login')
    }

    private networkError() {
        say.sayError('网络错误')
    }

    public handlePromise(promise: Promise<Response>) {
        promise.then(async response => {
            if (response.status === 401) {
                this.fail()
            } else {
                let json = await response.json()
                this.success(json)
            }
        }).catch(err => this.networkError())
    }
}